package prototype.protocol.thrift;

import org.apache.commons.lang3.Validate;
import org.apache.thrift.TBase;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;

public class Serializer {
	@SuppressWarnings("rawtypes")
	public static <T extends TBase> byte[] serialize(T obj) throws SerializationException {
		Validate.notNull(obj, "Cannot serialize from a null object");
		try {
			TSerializer util = new TSerializer();
			return util.serialize(obj);
		} catch (TException e) {
			throw new SerializationException(String.format("Failed to serialize from class %s", (obj == null ? null
					: obj.getClass())), e);
		}
	}

	@SuppressWarnings("rawtypes")
	public static <T extends TBase> void deserialize(T obj, byte[] bytes) throws SerializationException {
		Validate.notNull(obj, "Cannot deserialize into a null object");
		Validate.notNull(bytes, "Source serialized bytes cannot be null");
		try {
			TDeserializer util = new TDeserializer();
			util.deserialize(obj, bytes);
		} catch (TException e) {
			throw new SerializationException(String.format("Failed to deserialize into class %s", (obj == null ? null
					: obj.getClass())), e);
		}
	}

	public static class SerializationException extends Exception {
		private static final long serialVersionUID = -6661040575595101500L;

		public SerializationException(String message, Throwable throwable) {
			super(message, throwable);
		}
	}
}
